package com.fingard.dsp.bank.directbank.czcb01;

import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName CZCB01Transaction
 * @Author Zhengzy
 * @Date 2019/12/18 10:38
 * @Version 1.0
 **/
public class CZCB01Transaction extends CZCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        // 历史明细返回给ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        if (bankFront.userName == null || bankFront.userName == "") {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("无客户号节点或未配置客户号！");
            retAts.writeEnd();
            return retAts;
        }
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //按自然月循环查询
            int dateFrom = Integer.valueOf(p_req7516.dateFrom);
            int dateTo = Integer.valueOf(p_req7516.dateTo);
            int pageNumber = 20;// 请求记录条数 最多20
            int startRecord = 1;
            int totalRecords = 0;// 总记录条数
            int readedTotalRecords = 0;// 总读取记录条数
            while (dateFrom <= dateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                // 判断当页数据是否读完
                int returnRecords;// 返回当次请求记录条数
                int readedRecords = 0;// 已读当次请求记录条数记录条数

                Calendar tmpCalStep = Calendar.getInstance();
                tmpCalStep.setTime(tmpCalendarFrom.getTime());
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpCalStep.set(Calendar.DAY_OF_MONTH, tmpCalendarFrom.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpCalStep.setTime(tmpCalendarTo.getTime());
                }
                while (true) {
                    // 组装上送报文
                    XElement stream = new XElement("stream", "");// 内层明文
                    XmlTextWriter outTextWriter = new XmlTextWriter();// 外层报文

                    outTextWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"GBK\"?>");
                    outTextWriter.writeStartElement("CZBANK");


                    stream.addChild(new XElement("action", "BC0103"));
                    stream.addChild(new XElement("userName", bankFront.userName));
                    stream.addChild(new XElement("accountNo", p_req7516.actNum));
                    stream.addChild(new XElement("startDate", Format.Date8Format.format(tmpCalendarFrom.getTime())));
                    stream.addChild(new XElement("endDate", Format.Date8Format.format(tmpCalStep.getTime())));
                    stream.addChild(new XElement("pageNumber", pageNumber + ""));
                    stream.addChild(new XElement("startRecord", startRecord + ""));
                    startRecord = pageNumber + 1;

                    // 对明文报文进行加签加密  对xmlTextWriter进行加签加密
                    //String encryptData = stream.加签加密;

                    outTextWriter.writeXElement(stream); // 把明文组装入报文
                    outTextWriter.writeElementString("signData", "加签加密内容");// 把密文组装入报文
                    outTextWriter.writeEndElement();

                    // 发送报文到银行
                    String[] retStr = sendToBank(outTextWriter.toXmlString());

//                    String[] retStr = new String[]{"", "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
//                            "<CZBANK>\n" +
//                            "<stream>\n" +
//                            "<status>0000</status>\n" +
//                            "<statusText>明细查询成功</statusText>\n" +
//                            "<accountNo>1121</accountNo>\n" +
//                            "<accountName>郑章洋账号</accountName>\n" +
//                            "<openBankName>杭州银行</openBankName>\n" +
//                            "<totalRecords>2</totalRecords>\n" +
//                            "<returnRecords>2</returnRecords>\n" +
//                            "<list name=\"userDataList\">\n" +
//                            "<row>\n" +
//                            "<tranDate>20191201</tranDate>\n" +
//                            "<tranTime>111213</tranTime>\n" +
//                            "<sumTranNo></sumTranNo>\n" +
//                            "<tranAmount>100.00</tranAmount>\n" +
//                            "<creditDebitFlag>D</creditDebitFlag>\n" +
//                            "<oppAccountNo>1223</oppAccountNo>\n" +
//                            "<oppAccountName>对方账户名称</oppAccountName>\n" +
//                            "<oppOpenBankName>对方开户行名称</oppOpenBankName>\n" +
//                            "<abstract>转账</abstract>\n" +
//                            "<cashTransferFlag>0</cashTransferFlag>\n" +
//                            "<balance>111111.00</balance>\n" +
//                            "</row>\n" +
//                            "<row>\n" +
//                            "<tranDate>20191011</tranDate>\n" +
//                            "<tranTime>131313</tranTime>\n" +
//                            "<sumTranNo>355</sumTranNo>\n" +
//                            "<tranAmount>50.00</tranAmount>\n" +
//                            "<creditDebitFlag>C</creditDebitFlag>\n" +
//                            "<oppAccountNo>对方账号2</oppAccountNo>\n" +
//                            "<oppAccountName>对方账户名称</oppAccountName>\n" +
//                            "<oppOpenBankName>对方开户行名</oppOpenBankName>\n" +
//                            "<abstract>第二条记录</abstract>\n" +
//                            "<cashTransferFlag>1</cashTransferFlag>\n" +
//                            "<balance>5555.00</balance>\n" +
//                            "</row>\n" +
//                            "</list>\n" +
//                            "</stream>\n" +
//                            "<signData>密文</signData>\n" +
//                            "</CZBANK>\n"};
                    if (retStr[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(retStr[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpRetCode = tmpBkReader.getSimpleText("status");// 交易状态
                            String tmpRetInfo = tmpBkReader.getSimpleText("statusText");// 交易状态信息
                            returnRecords = Integer.parseInt(tmpBkReader.getSimpleText("returnRecords"));// 返回记录条数
                            totalRecords = Integer.parseInt(tmpBkReader.getSimpleText("totalRecords"));// 总记录条数
                            if ("0000".equals(tmpRetCode)) {
                                while (tmpBkReader.read("/CZBANK/stream/list/row")) {
                                    readedRecords++;// 当页的已读记录数
                                    readedTotalRecords++;// 总的已读记录数
                                    XElement tmpRecord = tmpBkReader.readedXElement;
                                    RetAtsTransDetail detail = new RetAtsTransDetail();
                                    detail.actNum = p_req7516.actNum;// 账号
                                    detail.recAccNum = tmpRecord.getSingleText("oppAccountNo");// 对方账号
                                    detail.recAccName = tmpRecord.getSingleText("oppAccountName");// 对方账户名称
                                    detail.recAccBank = tmpRecord.getSingleText("oppOpenBankName");// 对方开户行名
                                    detail.accBal = tmpRecord.getSingleTextNotNull("balance");// 账户余额
                                    String tranDate = tmpRecord.getSingleText("tranDate");// 交易日期 char(8) 格式YYYYMMDD
                                    String tranTime = tmpRecord.getSingleText("tranTime");// 交易时间 char(6) 格式hhmmss
                                    Date date = new DateFormat2("yyyyMMdd hh:mm:ss").parse(tranDate + " " + tranTime.substring(0, 2) + ":" + tranTime.substring(2, 4) + ":" + tranTime.substring(4, 6));
                                    detail.tranDate = Format.Date10Format.format(date);
                                    detail.tranTime = Format.DateTimeFormat.format(date);

                                    String cdFlag = tmpRecord.getSingleText("creditDebitFlag");
                                    String tranAmtStr = tmpRecord.getSingleText("tranAmount");
                                    if ("C".equals(cdFlag)) {
                                        if (tranAmtStr.indexOf("-") >= 0) {
                                            detail.cdFlag = "1";
                                        } else {
                                            detail.cdFlag = "2";// 贷
                                        }
                                    } else if ("D".equals(cdFlag)) {
                                        if (tranAmtStr.indexOf("-") >= 0) {
                                            detail.cdFlag = "2";
                                        } else {
                                            detail.cdFlag = "1";// 借
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "借贷标识: " + cdFlag + "无法识别";
                                        break;
                                    }
                                    detail.tranAmt = tranAmtStr.replace("-", "");
                                    detail.comment = tmpRecord.getSingleText("abstract");// 摘要，备注？
                                    // detail.askNumber = tmpRecord.getSingleText("sumTranNo");// 总交易流水号
                                    retAts.writeRetDetail(detail);
                                }
                                if (readedRecords == returnRecords || "-1".equals(tmpRespCode)) {
                                    // 当页数据读完了 发下一次请求 读取下一页
                                    break;
                                }
                            } else {
                                // 与0000相对
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpRetInfo;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = retStr[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpCalStep;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                dateFrom = Integer.valueOf(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }
}
